package example;

import client.DatabaseClient;
import dto.Request;
import dto.Response;

public class ClusterSyncAutoTest {
    public static void main(String[] args) throws Exception {
        // 1. 连接主节点，写入数据
        DatabaseClient masterClient = new DatabaseClient("localhost", 8888);
        masterClient.connect();
        System.out.println("连接主节点，写入数据...");
        masterClient.put("cluster_test_key", "cluster_test_value");
        masterClient.disconnect();

        // 2. 等待主从同步
        System.out.println("等待主从同步...");
        Thread.sleep(2000);

        // 3. 连接主节点读取数据
        masterClient = new DatabaseClient("localhost", 8888);
        masterClient.connect();
        String masterValue = masterClient.get("cluster_test_key", String.class);
        System.out.println("主节点读取结果: " + masterValue);
        masterClient.disconnect();

        // 4. 连接从节点1读取数据
        DatabaseClient slave1Client = new DatabaseClient("localhost", 8889);
        slave1Client.connect();
        String slave1Value = slave1Client.get("cluster_test_key", String.class);
        System.out.println("从节点1读取结果: " + slave1Value);
        slave1Client.disconnect();

        // 5. 连接从节点2读取数据
        DatabaseClient slave2Client = new DatabaseClient("localhost", 8890);
        slave2Client.connect();
        String slave2Value = slave2Client.get("cluster_test_key", String.class);
        System.out.println("从节点2读取结果: " + slave2Value);
        slave2Client.disconnect();

        // 6. 判断同步是否成功
        if ("cluster_test_value".equals(masterValue) &&
            "cluster_test_value".equals(slave1Value) &&
            "cluster_test_value".equals(slave2Value)) {
            System.out.println("主从同步测试成功！");
        } else {
            System.out.println("主从同步测试失败！");
        }

        // 7. 尝试在从节点1写入数据，应该失败并提示只读
        slave1Client = new DatabaseClient("localhost", 8889);
        slave1Client.connect();
        System.out.println("尝试在从节点1写入数据...");
        Response slave1PutResp = slave1Client.sendRequest(new Request(Request.RequestType.PUT) {{
            setKey("slave_write_test");
            setValue("should_fail");
            setValueType(String.class.getName());
        }});
        System.out.println("从节点1写入响应: " + slave1PutResp.getMessage());
        slave1Client.disconnect();

        // 8. 尝试在从节点2写入数据，应该失败并提示只读
        slave2Client = new DatabaseClient("localhost", 8890);
        slave2Client.connect();
        System.out.println("尝试在从节点2写入数据...");
        Response slave2PutResp = slave2Client.sendRequest(new Request(Request.RequestType.PUT) {{
            setKey("slave_write_test2");
            setValue("should_fail2");
            setValueType(String.class.getName());
        }});
        System.out.println("从节点2写入响应: " + slave2PutResp.getMessage());
        slave2Client.disconnect();
    }
} 